import gc,time,network,machine
from machine import WDT

global boot_count
try:
    # 尝试从非易失性存储中读取开机次数
    with open('boot_count.txt', 'r') as f:
        boot_count = int(f.read())
except:
    # 如果文件不存在，说明是第一次开机
    with open('boot_count.txt', 'w') as f:
        f.write(str(0))
    pass

def connect_wlan():
    station = network.WLAN(network.STA_IF)
    if not station.isconnected():
        ssid = "15367660966"
        password = "15367660"
        print("Connecting to WLAN ({})...".format(ssid))
        station.active(True)
        station.connect(ssid, password)
        while not station.isconnected():
            pass
    return True
def OTA():
    try:
        print("启动更新主程序看门狗")
        wdt = WDT(timeout=30000)
        print("连接wifi")
        connect_wlan()
        import senko
        gc.collect()
        OTA = senko.Senko(user="zhong-weisen", repo="ESP32", working_dir="Auto/", files=["Auto.py"])
        if OTA.update():
            print("更新成功")

    except Exception as e:
        print("更新失败",e)
        time.sleep(3)
        machine.reset()
def ota():
    if boot_count == 1:
        return True
    else:
        return False 

        
if __name__ == "__main__":
        if boot_count == 1:
            OTA()
            from Auto import *
            print("启动程序")
            auto()
        else:
            from Auto import *
            print("启动程序")
            auto()
